#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include "util.h"

void * BROW_MALLOC(size_t size) {   return malloc(size); }
void * BROW_REALLOC(void *p, size_t size) {  return realloc(p, size); }
void BROW_FREE(void * p) {  free(p); }

static struct dirent ** _names = NULL;
static int _len = 0;
static int _cur = -1;

int func_filter(const struct dirent * d)
{
    return (d->d_type & DT_REG);
}

int init_list_path(const char * path)
{
    _len = scandir(path, &_names, func_filter, alphasort);
    _cur = -1;
    return _len;
}

int uninit_list_path()
{
    if (_names) {
        while (_len--) {
            free(_names[_len]);
        }
        free(_names);
    }

    return 0;
}

const char * next_file(int skip)
{
    if (_len > 0) {
        _cur += skip;
        while (_cur < 0) {
            _cur += _len;
        }
        while (_cur >= _len) {
            _cur -= _len;
        }
        return _names[_cur]->d_name;
    }
    else {
        return NULL;
    }
}

const char * next_dir(int skip)
{
    return 0;
}

void rewind_all()
{
    _cur = -1;
}


